package com.demo.service.deepseek;

import com.demo.entity.riot.MatchInfo;
import com.demo.exception.ApiException;
import com.demo.service.riot.RiotMatchService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.demo.common.PdfExport;

@Service
public class PlayerAnalysisService {

    private final DeepSeekChatService deepSeekService;
    private final ObjectMapper objectMapper;
    private final RiotMatchService riotMatchService;
    private final PdfExportService pdfExportService;
    // 存储分批分析结果
    private final Map<String, List<MatchAnalysisResult>> analysisCache = new HashMap<>();

    private static final String ROLE_SETTING =
            "您是一名职业级LOL数据分析师，精通15.13版本meta。" +
                    "必须严格基于玩家位置(teamPosition)进行分析，所有结论必须引用具体数据字段值。使用中文进行汇报。";

    private static final String BATCH_OUTPUT_FORMAT =
            "{\"batch_id\":\"{{batch_number}}\"," +
                    "\"matches_analyzed\":[\"match_id1\",\"match_id2\"]," +
                    "\"summary\":{" +
                    "\"version_adaptation\":{" +
                    "\"rune_consistency\":0-1评分," +
                    "\"item_path_rating\":\"A-F评级\"}," +
                    "\"performance_trends\":{" +
                    "\"dmg_efficiency\":[场次1值,场次2值]," +
                    "\"survival_index\":[场次1值,场次2值]}," +
                    "\"position_insights\":[\"关键发现1\",\"关键发现2\"]}}";

    private static final String FINAL_OUTPUT_FORMAT =
            "# 玩家分析报告\n" +
                    "综合表现概览\n" +
                    "版本适应评估\n- 符文稳定性：{{rating}}/1.0\n" +
                    "关键发现\n1. {{trend_insight}}\n" +
                    "训练建议\n 即时调整\n- {{quick_fix}}";

    public PlayerAnalysisService(DeepSeekChatService deepSeekService,
                                 ObjectMapper objectMapper, RiotMatchService riotMatchService,
                                 PdfExportService pdfExportService) {
        this.deepSeekService = deepSeekService;
        this.objectMapper = objectMapper;
        this.riotMatchService = riotMatchService;
        this.pdfExportService = pdfExportService;
    }

    /**
     * 分批分析玩家对局数据
     * @param playerPuuid 玩家PUUID
     * @param batchSize 每批处理数量
     * @return 最终分析报告PDF路径
     */
    public List<String> analyzePlayerMatches(String serverRegion, String playerPuuid, int batchSize) throws JsonProcessingException, ApiException {
        analysisCache.put(playerPuuid, new ArrayList<>());

        List<MatchInfo> matches = riotMatchService.getMatchesByApi(serverRegion, playerPuuid, true);

        for (int i = 0; i < matches.size(); i += batchSize) {
            int end = Math.min(i + batchSize, matches.size());
            List<MatchInfo> batch = matches.subList(i, end);
            processBatch(playerPuuid, batch, i/batchSize + 1);
        }

        PlayerAnalysisReport finalReport = generateFinalReport(playerPuuid);

        List<String> list = List.of(finalReport.content.split("\n"));
        return list;
    }

    private void processBatch(String playerPuuid, List<MatchInfo> batch, int batchNumber) throws JsonProcessingException, ApiException {
        String prompt = buildBatchPrompt(playerPuuid, batch, batchNumber);
        String analysisResult = deepSeekService.chatCompletion(prompt);

        String r = extractJsonContent(analysisResult);

        MatchAnalysisResult result = objectMapper.readValue(r, MatchAnalysisResult.class);
        analysisCache.get(playerPuuid).add(result);
    }

    private String buildBatchPrompt(String playerPuuid, List<MatchInfo> batch, int batchNumber) {
        StringBuilder jsonData = new StringBuilder();
        for (MatchInfo match : batch) {
            jsonData.append(match.getRawJson()).append("\n\n");
        }

        return String.format(
                "# 英雄联盟玩家批次分析指令\n\n" +
                        "## 角色设定\n%s\n\n" +
                        "## 分析要求\n" +
                        "1. 分析玩家: %s\n" +
                        "2. 批次号: %d\n" +
                        "3. 分析维度:\n" +
                        "   - 版本适配性(符文/装备/目标参与)\n" +
                        "   - 核心指标(伤害效能/生存指数/资源转化)\n" +
                        "   - 位置专属分析(基于teamPosition)\n\n" +
                        "## 输出规范\n" +
                        "必须严格按以下JSON格式输出:\n" +
                        "%s\n\n" +
                        "## 对局数据\n%s",
                ROLE_SETTING,
                playerPuuid,
                batchNumber,
                BATCH_OUTPUT_FORMAT,
                jsonData.toString()
        );
    }

    private PlayerAnalysisReport generateFinalReport(String playerPuuid) throws ApiException, JsonProcessingException {
        List<MatchAnalysisResult> results = analysisCache.get(playerPuuid);
        String prompt = buildFinalReportPrompt(playerPuuid, results);
        String finalReport = deepSeekService.chatCompletion(prompt);
        return new PlayerAnalysisReport(playerPuuid, finalReport);
    }

    private String buildFinalReportPrompt(String playerPuuid, List<MatchAnalysisResult> results) throws JsonProcessingException {
        String summaryData;
        summaryData = objectMapper.writeValueAsString(results);

        return String.format(
                "# 英雄联盟玩家最终分析指令\n\n" +
                        "## 角色设定\n%s\n\n" +
                        "## 分析要求\n" +
                        "1. 玩家: %s\n" +
                        "2. 总场次: %d\n" +
                        "3. 分析维度:\n" +
                        "   - 跨场次表现趋势\n" +
                        "   - 稳定性评估\n" +
                        "   - 版本适应性问题\n\n" +
                        "## 输出规范\n" +
                        "必须按以下Markdown格式输出报告:\n" +
                        "%s.\n\n"
                        + "## 现在我提供分批分析结果\n%s",
                ROLE_SETTING,
                playerPuuid,
                results.size(),
                FINAL_OUTPUT_FORMAT,
                summaryData
        );
    }

    private String extractJsonContent(String response) {
        // 定义标记
        final String startMarker = "```json";
        final String endMarker = "```";

        // 查找起始位置
        int startIndex = response.indexOf(startMarker);
        if (startIndex == -1) {
            // 如果没有起始标记，直接返回原内容
            return response;
        }
        startIndex += startMarker.length();

        // 查找结束位置
        int endIndex = response.lastIndexOf(endMarker);
        if (endIndex == -1 || endIndex <= startIndex) {
            // 如果没有结束标记或标记位置无效
            return response.substring(startIndex).trim();
        }

        // 提取并清理内容
        String extracted = response.substring(startIndex, endIndex).trim();

        // 处理可能的前导/尾随字符
        if (extracted.startsWith("\n") || extracted.startsWith("\r")) {
            extracted = extracted.substring(1);
        }
        if (extracted.endsWith("\n") || extracted.endsWith("\r")) {
            extracted = extracted.substring(0, extracted.length() - 1);
        }

        return extracted;
    }


    // PDF导出服务（简化示例）
    @Service
    public static class PdfExportService {

        // 默认导出目录
        private static final String DEFAULT_EXPORT_DIR = "reports/";

        // 默认中文字体路径（根据系统调整）
        private static final String DEFAULT_CHINESE_FONT = "C:/Windows/Fonts/simhei.ttf";

        // 默认字号
        private static final float DEFAULT_FONT_SIZE = 12f;

        public String exportToPdf(PlayerAnalysisReport report) {
            // 创建PDF文件路径
            String fileName = report.getPlayerPuuid() + "_analysis_" +
                    System.currentTimeMillis() + ".pdf";
            String filePath = DEFAULT_EXPORT_DIR + fileName;

            try {
                // 确保目录存在
                new File(DEFAULT_EXPORT_DIR).mkdirs();

                // 导出PDF
                PdfExport.exportTextToPdf(
                        report.getContent(),
                        filePath,
                        DEFAULT_CHINESE_FONT,
                        DEFAULT_FONT_SIZE
                );

                return filePath;

            } catch (IOException e) {
                System.err.println("PDF导出失败: " + e.getMessage());
                // 返回默认路径（即使导出失败也保持接口一致性）
                return DEFAULT_EXPORT_DIR + fileName;
            }
        }
    }

    // 数据模型
    public static class MatchAnalysisResult {
        private String batch_id;
        private List<String> matches_analyzed;
        private Map<String, Object> summary;

        public String getBatch_id() {
            return batch_id;
        }

        public void setBatch_id(String batch_id) {
            this.batch_id = batch_id;
        }

        public Map<String, Object> getSummary() {
            return summary;
        }

        public void setSummary(Map<String, Object> summary) {
            this.summary = summary;
        }

        public List<String> getMatches_analyzed() {
            return matches_analyzed;
        }

        public void setMatches_analyzed(List<String> matches_analyzed) {
            this.matches_analyzed = matches_analyzed;
        }

        // getters/setters
    }

    public static class PlayerAnalysisReport {
        private String playerPuuid;
        private String content;

        public PlayerAnalysisReport(String playerPuuid, String content) {
            this.playerPuuid = playerPuuid;
            this.content = content;
        }

        public String getPlayerPuuid() {
            return playerPuuid;
        }

        public void setPlayerPuuid(String playerPuuid) {
            this.playerPuuid = playerPuuid;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        // constructor/getters/setters
    }
}
